package com.agou.core.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Random;

public class UtSequence {
	private static String s_id = "unknown";
	private static SecureRandom mySecureRand = new SecureRandom();
	private static Random myRand = new Random();

	private static long keyTimestamp = 0;

	static {
		keyTimestamp = System.currentTimeMillis();
		// 可能会存在多台主机，每一财
	}

	static {
		try {
			s_id = InetAddress.getLocalHost().toString();
		} catch (UnknownHostException e) {// 异常不处理
			e.getMessage();
		}
	}

	// 产生唯一值
	public static String genRandomGUID() {
		return genRandomGUID(false);
	}

	// 产生唯一值
	public static String genRandomGUID(boolean secure) {
		String valueBeforeMD5 = "";
		String valueAfterMD5 = "";

		MessageDigest md5 = null;
		StringBuffer sbValueBeforeMD5 = new StringBuffer();
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			System.out.println("Error: " + e);
			return valueBeforeMD5;
		}

		long time = System.currentTimeMillis();
		long rand = 0L;

		if (secure) {
			rand = mySecureRand.nextLong();
		} else {
			rand = myRand.nextLong();
		}

		sbValueBeforeMD5.append(s_id);
		sbValueBeforeMD5.append(":");
		sbValueBeforeMD5.append(Long.toString(time));
		sbValueBeforeMD5.append(":");
		sbValueBeforeMD5.append(Long.toString(rand));
		valueBeforeMD5 = sbValueBeforeMD5.toString();
		md5.update(valueBeforeMD5.getBytes());
		byte[] array = md5.digest();

		String strTemp = "";
		for (int i = 0; i < array.length; i++) {
			strTemp = Integer.toHexString(array[i] & 0xFF);
			if (strTemp.length() == 1) {
				valueAfterMD5 = valueAfterMD5 + "0" + strTemp;
			} else {
				valueAfterMD5 = valueAfterMD5 + strTemp;
			}
		}

		return valueAfterMD5.toUpperCase();
	}

	public static long genRandomNum() {
		// long 长度最大 19位 时间戳是 18位
		return nextKeyTimestamp();
	}

	private static long nextKeyTimestamp() {
		keyTimestamp++;
		return keyTimestamp;
	}
}
